//项目管理
import * as React from 'react';
import {
  TreeSelect,
  Modal,
  Row,
  Col,
  DatePicker,
  notification,
  Menu,
  Steps,
  Dropdown,
  Icon,
  Input,
  Table,
  Button,
  Form,
  InputNumber,
  Tabs,
  Spin,
  Tooltip,
  Select
} from 'antd';

import router from 'umi/router';
import Link from 'umi/link';
import { formatTreeData } from '../../components/commonAips';
import axios from 'axios';
import Api from '../../services/apis';
import { connect } from 'dva';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import moment from 'moment';
import 'moment/locale/zh-cn';
import { func } from 'prop-types';
import styles from './style.less'

const confirm = Modal.confirm;
const TabPane = Tabs.TabPane;
const { RangePicker } = DatePicker;
const Step = Steps.Step;
const Option = Select.Option;
const FormItem = Form.Item;

@connect(({ user, project, activities, chart, loading }) => ({
  currentUser: user.currentUser,
  currentUserLoading: loading.effects['user/fetchCurrent']
}))
class projectManagement extends React.Component {
  constructor(props) {
    super(props);
    // const token = sessionStorage.getItem('tokenData') ? sessionStorage.getItem('tokenData') : '';
    this.state = {
      name: '',
      tranUnits: '',
      pageSize: 5,
      current: 1,
      tableData: [],
      modalVisible: false,
      selectdIds: [],
      ownerStatus: [],
      ownerType: [],
      signStatus: [],
      assetStatus: [],

      showDownload: false,
      downloadName: '',
      downloadLink: '',
      startDownload: false,
    };
  }
  //获取表格数据
  sendData = () => {
    let that = this;
    this.setState({ loading: true })
    axios.post(Api.amGetProList, {
      currentPage: that.state.current,
      projectName: that.state.name,
      transferUnit: that.state.tranUnits
    })
      .then(function (resp) {
        console.log(resp)
        const data = resp.data;
        if (data.list.length == 0) {
          notification.destroy();
          notification['warning']({
            message: '暂无数据',
          });
        }

        data.list.forEach((d, i) => {
          d.key = i;
          d.receivedDate = moment(d.receivedDate).format("YYYY-MM-DD HH:mm:ss")
        })

        that.setState({
          tableData: data.list,
          pageSize: data.pageSize,
          current: data.currentPage,
          total: data.totalSize
        })
        that.setState({ loading: false })
      })
  };

  componentWillMount() {
    const that = this;
    that.sendData();

    //获取系统参数
    axios.all([this.getSysDic("OWNER_SHIP_STATUS"), this.getSysDic("OWNER_SHIP_TYPE"), this.getSysDic("SIGN_STATUS"), this.getSysDic("ASSET_STATUS")])
      .then(axios.spread(function (r1, r2, r3, r4) {
        that.setState({
          ownerStatus: r1.data, //权证状态
          ownerType: r2.data,  //权证类型
          signStatus: r3.data,  //签署协议状态
          assetStatus: r4.data,  //资产状态
        })
      }))

    //获取挂接楼盘跳转传参
    const routerData = this.props.location.query;
    if (routerData.projectCode) {
      this.getProject(routerData.projectCode);
    }
  }

  ///获取系统参数
  getSysDic = (type) => {
    return axios.post(Api.amGetSysDic, { key: type })
  }

  //查询
  query = () => {
    this.setState({ current: 1 }, () => {
      this.sendData();
    });
  };

  //获取项目
  getProject = (id) => {
    this.setState({ loading: true })
    this.setState({ projectCode: id })
    const that = this;
    axios.post(Api.amGetProInfo, { projectCode: id })
      .then(function (resp) {
        const { data } = resp;
        that.props.form.setFieldsValue({
          projectCode: data.projectCode,
          projectName: data.projectName,
          coveredArea: data.coveredArea,
          transferUnit: data.transferUnit,
          manageType: data.manageType,
          receiveDate: data.receiveDate ? moment(data.receiveDate) : null,
          obtainWay: data.obtainWay,
          houseCount: data.houseCount,
          buildCount: data.buildCount,
          landArea: data.landArea,
          obtainWay: data.obtainWay,
          manageType: data.manageType
        });

        that.setModalVisible(true);
        that.setState({ loading: false });
      })
  };

  //删除项目
  deleteProject = (id) => {
    const that = this;
    confirm({
      title: "删除确认",
      content: '确认删除该项目？',
      onOk() {
        that.setState({ loading: true })
        axios.post(Api.amDelProjectInfo, { projectCode: id })
          .then(function (resp) {
            const { data } = resp;
            if (data.code == 1) {
              notification.destroy();
              notification['success']({ message: data.msg });
              that.sendData();
            } else {
              notification.destroy();
              notification['warning']({ message: data.msg });
            }
            that.setState({ loading: false })
          })
      }
    })
  }

  //编辑项目(点弹框确定)
  editProject = () => {
    let that = this;
    this.setState({ loading: true })

    this.props.form.validateFields((err, values) => {
      if (!err) {
        axios.post(Api.amUpdateProInfo, {
          projectCode: values.projectCode,
          projectName: values.projectName,
          transferUnit: values.transferUnit,
          manageType: values.manageType,
          obtainWay: values.obtainWay,
          landArea: values.landArea,
          communityName: values.communityName,
        })
          .then(function (resp) {
            const { data } = resp;
            if (data.code == 1) {
              notification.destroy();
              notification['success']({ message: data.msg });
              that.sendData();
              that.setModalVisible(false);
            } else if (data.code == 0) {
              notification.destroy();
              notification['error']({ message: data.msg });
            }
            that.setState({ loading: false })
          })
      }
    })
  };

  //导出
  export = () => {
    if (this.state.selectdIds.length != 0) {
      const param = this.state.selectdIds.join(',');
      this.setState({
        startDownload: false
      });
      axios.get(Api.amExportPro, {
        params: {
          proCodes: param,
        },
        responseType: 'arraybuffer'
      }).then((res) => {
        notification.destroy();
        notification['success']({ message: '开始下载！' })

        let blob = new Blob([res.data], { type: "application/vnd.ms-excel" });
        const [dLink, name] = [
          window.URL.createObjectURL(blob),
          `项目列表${new Date().toLocaleDateString()} ${new Date().toLocaleTimeString()}.xls`
        ];
        let link = document.createElement('a');
        link.href = dLink;
        link.download = name;
        link.click();
        this.setState({
          startDownload: true,
          downloadLink: dLink,
          downloadName: name,
          showDownload: true
        });
      }).catch((err) => {
        notification.destroy();
        notification['warning']({ message: `下载失败！错误信息：${err}` })
      });
    } else {
      notification.destroy();
      notification['warning']({ message: '请选择表格中的项后进行导出！' })
    }
  };

  showDownload(showDownload) {
    this.setState({ showDownload });
  }

  changeName = e => {
    this.setState({ name: e.target.value });
  };

  changeTranUnits = e => {
    this.setState({ tranUnits: e.target.value });
  };

  pageChange = page => {
    this.setState(
      {
        current: page,
      },
      () => {
        this.sendData();
      }
    );
  };

  setModalVisible = visible => {
    this.setState({ modalVisible: visible });
  };

  changeSelected = (selectedRowKeys, selectedRows) => {
    let selectdIds = [];
    selectedRows &&
      selectedRows.forEach((d, i, arr) => {
        selectdIds.push(d.projectCode);
      });

    this.setState({ selectedArr: selectedRowKeys, selectdIds: selectdIds });
  };


  handleMenuClick = (project) => {
    var win = window.open('/fe/assetManagement/projectInfo?projectCode=' + project.projectCode, '_blank');
    win.focus();
  }

  //挂接楼盘跳转
  goUploadResult = () => {
    router.push({
      pathname: '/fe/assetManagement/dataCorrection',
      state: {
        projectCode: this.state.projectCode,
        showBack: true,
        type: 'projectManagement'
      }
    })
  }

  render() {
    let that = this;
    const { form: { getFieldDecorator }, currentUserLoading } = this.props;

    //表格表头
    const columns = [
      {
        title: '项目名称',
        dataIndex: 'projectName',
        key: 'projectName',
        render: (text, item, index) => (
          <a href="javascrip:;" onClick={this.handleMenuClick.bind(this, item)}>
            {text}
          </a>
        ),
      },
      {
        title: '项目编号',
        dataIndex: 'projectCode',
        key: 'projectCode',
      },
      {
        title: '建筑面积',
        dataIndex: 'coveredArea',
        key: 'coveredArea',
      },
      {
        title: '划转单位',
        dataIndex: 'transferUnit',
        key: 'transferUnit',
      },
      {
        title: '楼栋数量',
        dataIndex: 'buildCount',
        key: 'buildCount',
        render: (text, item, index) => {
          return text == 0 ? 0 :
            (
              <Link
                key={index}
                target='_blank'
                to={{
                  pathname: '/fe/assetManagement/buildingManagement',
                  search: `?id=${item.projectCode}&communityName=${item.communityName}&manageType=${item.manageType}&transferUnit=${item.transferUnit}&projectName=${item.projectName}`
                }}
              >
                {text}
              </Link>
            )
        },
      },
      {
        title: '房屋数量',
        dataIndex: 'houseCount',
        key: 'houseCount',
      },
      {
        title: '接收时间',
        dataIndex: 'receivedDate',
        key: 'receivedDate',
      },
      {
        title: '操作',
        dataIndex: 'action',
        key: 'action',
        render: (text, item, index) => (
          <span>
            <a href="javascript:;" onClick={this.getProject.bind(this, item.projectCode)}>编辑</a>&emsp;
              <a href="javascript:;" onClick={this.deleteProject.bind(this, item.projectCode)}>删除</a>
          </span>
        ),
      },
    ];

    const rowSelection = {
      selectedRowKeys: this.state.selectedArr,
      onChange: (selectedRowKeys, selectedRows) => {
        this.changeSelected(selectedRowKeys, selectedRows);
      },
    };

    return (
      <PageHeaderWrapper
        loading={currentUserLoading}
      >
        <div className="mainContainer">
          <div className='contentHeader'>
            <div className="contentHeaderTitle">
              <p>项目管理</p>
              <p>PROJECT MANAGEMENT</p>
            </div>
          </div>
          <Form layout="inline" align='center'>
            <FormItem>
              <span className="label">项目名称</span>
              <Input
                value={this.state.name}
                data-inp="zdbh"
                onChange={this.changeName}
                placeholder="请输入项目名称"
              />
            </FormItem>

            <FormItem>
              <span className="label">划转单位</span>
              <Input
                value={this.state.tranUnits}
                data-inp="zdbh"
                onChange={this.changeTranUnits}
                placeholder="请输入划转单位"
              />
            </FormItem>

            <Row>
              <Col span={24} style={{ textAlign: 'center', marginBottom: '10px' }}>
                <Button icon="search" type="primary" className="evfilterbtn" onClick={this.query}>
                  搜索
                </Button>
                &emsp;
                <Button icon='profile' ghost
                  onClick={this.export}
                  type="primary"
                  htmlType="reset"
                  className="evfilterbtn"
                >
                  生成报表
                </Button>
              </Col>
            </Row>
          </Form>

          <Spin spinning={this.state.loading}>
            <Row>
              <Table
                bordered={true}
                scroll={{ x: true }}
                columns={columns}
                dataSource={this.state.tableData}
                rowSelection={rowSelection}
                pagination={{
                  defaultPageSize: that.state.pageSize,
                  current: that.state.current,
                  onChange: that.pageChange,
                  total: that.state.total,
                  showTotal: total => `共 ${total} 项`
                }}
              />
            </Row>

            <Modal
              title="开始下载"
              visible={this.state.showDownload}
              width={400}
              wrapClassName="vertical-center-modal"
              onOk={this.showDownload.bind(this, false, 'ok')}
              onCancel={this.showDownload.bind(this, false, 'cancel')}
              style={{
                textAlign: 'center'
              }}
            >
              {this.state.downloadName !== '' ?
                <div>
                  <p>开始自动下载...</p>
                  <p><a download={this.state.downloadName} href={this.state.downloadLink}>下载没有开始，点击此链接手动下载。</a></p>
                </div>
                :
                <div>
                  <p>文件生成中，请稍后。</p>
                  <p><Icon type="loading" /></p>
                </div>
              }
            </Modal>

            <Modal
              title="编辑项目"
              wrapClassName="vertical-center-modal"
              visible={this.state.modalVisible}
              onOk={this.editProject}
              onCancel={() => this.setModalVisible(false)}
              width={830}
            >
              <Row gutter={24}>
                <Col span={8}>
                  <FormItem label="项目编号：">
                    {getFieldDecorator('projectCode', {
                      rules: [{ required: true, message: '请输入项目编号！' }]
                    })(<Input placeholder="请输入项目编号" disabled />)}
                  </FormItem>
                </Col>
                <Col span={8}>
                  <FormItem label="项目名称：">
                    {getFieldDecorator('projectName', {
                      rules: [{ required: true, message: '请输入项目名称！' }]
                    })(<Input placeholder="请输入项目名称" />)}
                  </FormItem>
                </Col>
                <Col span={8}>
                  <FormItem label="建筑面积：">
                    {getFieldDecorator('coveredArea', {
                      rules: [{ required: true, message: '请输入建筑面积！' },
                      { pattern: /^[0-9]+([.]{1}[0-9]+){0,1}$/, message: '请输入数值！' }]
                    })(<Input placeholder="请输入建筑面积" />)}
                  </FormItem>
                </Col>
                <Col span={8}>
                  <FormItem label="划转单位：">
                    {getFieldDecorator('transferUnit', {
                      rules: [{ required: true, message: '请输入划转单位！' }]
                    })(<Input placeholder="请输入划转单位" />)}
                  </FormItem>
                </Col>
                <Col span={8}>
                  <FormItem label="管理方式：">
                    {getFieldDecorator('manageType')(
                      <Select placeholder="请选择管理方式" style={{ width: "100%" }} disabled>
                        <Option value='自管'>自管</Option>
                        <Option value='托管'>托管</Option>
                      </Select>)}
                  </FormItem>
                </Col>
                <Col span={8}>
                  <FormItem label="接管时间：">
                    {getFieldDecorator('receiveDate')(<DatePicker disabled style={{ width: "100%" }} />)}
                  </FormItem>
                </Col>
                <Col span={8}>
                  <FormItem label="取得方式：">
                    {getFieldDecorator('obtainWay')(<Select placeholder="请选择取得方式" style={{ width: "100%" }} disabled>
                      <Option value='划转'>划转</Option>
                      <Option value='收购'>收购</Option>
                    </Select>)}
                  </FormItem>
                </Col>
                <Col span={8}>
                  <FormItem label="总房屋数：">
                    {getFieldDecorator('houseCount')(<Input placeholder="请输入总房屋数" disabled />)}
                  </FormItem>
                </Col>
                <Col span={8}>
                  <FormItem label="总楼栋数：">
                    {getFieldDecorator('buildCount')(<Input placeholder="请输入总楼栋数" disabled />)}
                  </FormItem>
                </Col>
                <Col span={8}>
                  <FormItem label="土地面积：">
                    {getFieldDecorator('landArea', {
                      rules: [{ required: true, message: '请输入土地面积！' },
                      { pattern: /^[0-9]+([.]{1}[0-9]+){0,1}$/, message: '请输入数值！' }]
                    })(<Input placeholder="请输入土地面积" />)}
                  </FormItem>
                </Col>
                <Col span={8}>
                  <div className={styles.formLabel}>&emsp;挂接楼盘：<br />
                    <Icon type="compass" theme="twoTone" className={styles.iconButton} onClick={this.goUploadResult} />
                  </div>
                </Col>
              </Row>
            </Modal>
          </Spin>
        </div>
      </PageHeaderWrapper>
    );
  }
}

const WrappedApp = Form.create()(projectManagement);
export default WrappedApp;